package com.example.hosptial.service.impl;

import com.example.hosptial.model.enity.Department;
import com.example.hosptial.model.enity.Doctor;
import com.example.hosptial.model.view.DoctorView;
import com.example.hosptial.repository.DepartmentRepository;
import com.example.hosptial.repository.DoctorRepository;
import com.example.hosptial.repository.DoctorViewRepository;
import com.example.hosptial.service.DoctorManagementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DoctorManagementServiceImpl implements DoctorManagementService {
    private static final Logger logger = LoggerFactory.getLogger(DoctorManagementServiceImpl.class);

    @Autowired
    private DoctorRepository doctorRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private DoctorViewRepository doctorViewRepository;

    @Override
    public List<Department> getAllDepartments() {
        logger.info("Getting all departments");
        List<Department> departments = departmentRepository.findAll();
        logger.info("Found {} departments", departments.size());
        departments.forEach(dept -> 
            logger.debug("Department: ID={}, Name={}", dept.getDeptId(), dept.getDeptName())
        );
        return departments;
    }

    @Override
    public List<DoctorView> getAllDoctors() {
        logger.info("Getting all doctors");
        List<DoctorView> doctors = doctorViewRepository.findAll();
        logger.info("Found {} doctors", doctors.size());
        doctors.forEach(doctor -> 
            logger.debug("Doctor: ID={}, Name={}, Department={}", 
                doctor.getDoctorId(), doctor.getDoctorName(), doctor.getDeptName())
        );
        return doctors;
    }

    @Override
    public List<DoctorView> getDoctorsByDepartment(Integer deptId) {
        logger.info("Getting doctors for department ID: {}", deptId);
        if (deptId == null || deptId <= 0) {
            logger.error("Invalid department ID: {}", deptId);
            throw new IllegalArgumentException("无效的科室ID");
        }
        List<DoctorView> doctors = doctorViewRepository.findByDeptId(deptId);
        logger.info("Found {} doctors in department {}", doctors.size(), deptId);
        doctors.forEach(doctor -> 
            logger.debug("Doctor: ID={}, Name={}", doctor.getDoctorId(), doctor.getDoctorName())
        );
        return doctors;
    }

    @Override
    public List<DoctorView> searchDoctorsByName(String doctorName) {
        if (doctorName == null || doctorName.trim().isEmpty()) {
            throw new IllegalArgumentException("医生姓名不能为空");
        }
        return doctorViewRepository.findByDoctorNameContaining(doctorName.trim());
    }

    @Override
    @Transactional
    public Doctor addDoctor(Doctor doctor) {
        // 验证科室是否存在
        Department department = departmentRepository.findById(doctor.getDepartment().getDeptId())
                .orElseThrow(() -> new IllegalArgumentException("指定的科室不存在"));
        
        // 设置正确的科室对象
        doctor.setDepartment(department);
        
        // 保存医生信息
        return doctorRepository.save(doctor);
    }

    @Override
    @Transactional
    public DoctorView updateDoctorInfo(String doctorId, String currentPassword,
                                     String newPhone, String newPassword) {
        // 首先通过视图验证密码
        DoctorView doctorView = doctorViewRepository.findByDoctorId(doctorId)
                .orElseThrow(() -> new IllegalStateException("医生信息不存在"));

        // 验证当前密码
        if (!doctorView.getDoctorPassword().equals(currentPassword)) {
            throw new IllegalArgumentException("当前密码错误");
        }

        // 获取医生实体并更新信息
        Doctor doctor = doctorRepository.findByDoctorId(doctorId);
        if (doctor == null) {
            throw new IllegalStateException("医生信息不存在");
        }

        // 更新信息
        if (newPhone != null && !newPhone.trim().isEmpty()) {
            doctor.setDoctorPhone(newPhone);
        }
        
        // 只有当新密码不为空时才更新密码
        if (newPassword != null && !newPassword.trim().isEmpty()) {
            doctor.setDoctorPassword(newPassword);
        }
        
        doctorRepository.save(doctor);

        // 返回更新后的医生视图信息
        return doctorViewRepository.findByDoctorId(doctorId)
                .orElseThrow(() -> new IllegalStateException("无法获取更新后的医生信息"));
    }
}